
// 148.排序链表
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {

    // 将两个链表进行合并
    ListNode* _Merge_Base(ListNode* head1 , ListNode* head2)
    {
        ListNode* phead = new ListNode ,  *tail = phead;
        while(head1 || head2)
        {
            if(head2 == nullptr || (head1 && head1->val < head2->val))
            {
                tail->next = head1;
                tail = tail->next;
                head1 = head1->next;
            }
            else 
            {
                tail->next = head2;
                tail = tail->next;
                head2 = head2->next;
            }
        }
        ListNode *ret = phead->next;
        delete phead;
        return ret;
    }


public:
    ListNode* sortList(ListNode* head) {
        // 使用归并排序
        constexpr int  sz = 64;
        vector<ListNode*> lists(sz , nullptr);


        int fill = 0;
        ListNode* cur = head;
        while(cur)
        {
            ListNode *tmp = cur;
            cur = cur->next;
            tmp->next = nullptr;
            int i = 0 ;
            while(lists[i])
            {
                tmp = _Merge_Base(tmp , lists[i]);
                lists[i++] = nullptr;
            }
            lists[i] = tmp;
            if(i == fill) fill++;
        }
        // 最后再将所有链表进行合并
        ListNode* ret = nullptr;
        for(int i = 0 ; i < fill ; i++)
            if(lists[i]) ret = _Merge_Base(ret , lists[i]);

        return ret;
    }
};